<template>
  <md-page title="比赛作弊举报" isBtn :btnTextItems="data.btnTextItems" @btnClick="bottomBtnClick">
    <view class="container">
      <uni-forms ref="form" :modelValue="data.formData" :rules="data.rules" label-position="top" label-width="100">
        <!-- 证明照片 -->
        <uni-forms-item label="证明照片" name="images" required>
          <view class="upload-section">
            <uni-file-picker
              v-model="data.formData.images"
              limit="3"
              title="最多选择3张图片"
              file-mediatype="image"
              @select="handleUpload"
              @delete="handleDelete" />
            <view class="upload-tip">请上传相关图片作为举报证据（最多3张）</view>
          </view>
        </uni-forms-item>

        <!-- 作弊类型 -->
        <uni-forms-item label="作弊类型" name="reason" required>
          <uni-easyinput
            type="textarea"
            v-model="data.formData.reason"
            placeholder="请详细描述作弊情况，如：该选手在比赛过程中使用交通工具、抄近道等"
            :maxlength="500"
            :showWordLimit="true"
            :input-border="false" />
        </uni-forms-item>

        <!-- 作弊选手号码 -->
        <uni-forms-item label="作弊选手号码" name="reamrk" required>
          <uni-easyinput
            v-model="data.formData.reamrk"
            placeholder="请输入作弊选手的号码"
            type="text"
            :maxlength="50"
            :input-border="false" />
        </uni-forms-item>
      </uni-forms>
    </view>
  </md-page>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { report, uploadImage } from '@/api';
import { Toast } from '@/utils/util';
import type { BtnTextItem } from '@/components/md-ui/components/md-page/md-page.vue';
import { ReportSourceType } from '@/api/enum';

const data = reactive<any>({
  btnTextItems: [],
  formData: {
    images: [],
    reason: '',
    reamrk: '',
  },
  rules: {
    images: {
      rules: [
        {
          required: true,
          errorMessage: '请上传证明照片',
        },
      ],
    },
    reason: {
      rules: [
        {
          required: true,
          errorMessage: '请填写作弊类型',
        },
      ],
    },
    reamrk: {
      rules: [
        {
          required: true,
          errorMessage: '请输入作弊选手号码',
        },
      ],
    },
  },
});

const form = ref<any>(null);

/**
 * 上传相关
 */
const handleUpload = async (e: any) => {
  console.log('选择文件：', e);
  let { tempFilePaths } = e;

  if (!tempFilePaths || tempFilePaths.length === 0) return;

  uni.showLoading({
    title: '图片上传中...',
    mask: true,
  });

  try {
    let uploadTasks = tempFilePaths.map(async (filePath: string) => {
      let res = await uploadImage({ filePath, formData: { category: 'report' } });
      const url = res.data.url;
      const name = url?.split?.('/')?.slice(-1);
      // 格式化组件需要的格式
      return {
        url,
        extname: 'png',
        name,
      };
    });

    const uploadedImages = await Promise.all(uploadTasks);
    data.formData.images = [...data.formData.images, ...uploadedImages];

    uni.hideLoading();
    // console.log('所有图片上传成功', uploadedImages);
  } catch (error) {
    uni.hideLoading();
    Toast('图片上传失败，请重试');
    console.error('图片上传失败:', error);
  }
};

const handleDelete = (e: any) => {
  // console.log('删除文件：', e);
  data.formData.images = data.formData.images.filter((item: any, index: number) => index !== e.index);
};

/**
 * 底部按钮点击事件
 */
const bottomBtnClick = async (info: { item: BtnTextItem }) => {
  const { key } = info.item;

  if (key === 'submit') {
    try {
      // 表单验证
      await form.value?.validate();

      // 额外验证：确保图片不为空
      if (!data.formData.images || data.formData.images.length === 0) {
        Toast('请上传证明照片');
        return;
      }

      // 确认提交
      uni.showModal({
        title: '确认提交',
        content: '确认提交举报信息吗？提交后将无法修改。',
        success: async modalRes => {
          if (modalRes.confirm) {
            await submitReport();
          }
        },
      });
    } catch (error: any) {
      // 表单验证失败
      if (error?.length) {
        Toast(error[error.length - 1]?.errorMessage || '请完善表单信息');
      }
    }
  }
};

/**
 * 提交举报
 */
const submitReport = async () => {
  try {
    uni.showLoading({
      title: '提交中...',
      mask: true,
    });

    // 调用举报API
    const submitData = {
      ...data.formData,
      images: data.formData.images.map((img: any) => img.url).join(','),
      source_id: 0,
      source_type: ReportSourceType.比赛,
    };
    const res = await report(submitData);

    uni.hideLoading();

    uni.showModal({
      title: res?.msg || '举报提交成功，我们会尽快处理',
      showCancel: false,
      success(res) {
        if (res.confirm) {
          // 返回上一页
          uni.navigateBack();
        }
      },
    });
  } catch (error) {
    uni.hideLoading();
    Toast('提交失败，请重试');
    console.error('提交举报失败:', error);
  }
};

onLoad(() => {
  // 设置底部按钮
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  const commonStyle = (type: number) => ({
    color: configInfo?.['button_color' + type] || '#d92121',
    textColor: configInfo?.['button_color' + type + '_text'] || '#ffffff',
  });

  data.btnTextItems = [
    {
      text: '提交举报',
      key: 'submit',
      ...commonStyle(1),
    },
  ];
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  min-height: calc(100vh - 200rpx);

  .upload-section {
    .upload-tip {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
      line-height: 1.4;
    }
  }

  :deep(.uni-forms-item) {
    margin-bottom: 40rpx;

    .uni-forms-item__label {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 20rpx;
    }

    .uni-easyinput__content {
      border-radius: 10rpx;
      border: 2rpx solid #e5e5e5;

      .uni-easyinput__content-input {
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  :deep(.uni-file-picker) {
    .uni-file-picker__container {
      border-radius: 10rpx;
      border: 2rpx dashed #e5e5e5;

      .uni-file-picker__input-box {
        background-color: #f8f8f8;
      }
    }
  }
}
</style>
